import {getRepository} from "typeorm";
import { Borrow } from "../entity/Borrow";

class BorrowServer {

  // 添加借阅记录（借书）
  async addBorrow(BorrowInfo:Borrow) {
    const borrowRepository = getRepository(Borrow);
    const borrow = borrowRepository.create(BorrowInfo);
    return borrowRepository.save(borrow);
  }

  // 修改借阅记录中的 if_back 为 "is" （还书）
  async updateBorrow(reader_id: number, book_id: string) {
    const borrowRepository = getRepository(Borrow);
    let borrow =  await borrowRepository.findOne({
      reader_id,
      book_id,
      if_back: 'no'
    })
    if (!borrow) return
    borrow.if_back = 'is'    
    return borrowRepository.save(borrow)
  }

  // 根据图书 id，在借阅记录中，查找该图书是否存在未归还（if_back 为 no）
  async findBookNoBorrow(book_id: string) {
    const borrowRepository = getRepository(Borrow);
    return borrowRepository.findOne({
      book_id,
      if_back: 'no'
    })
  } 

  // 查找所有借阅记录
  async findBorrows() {
    const borrowRepository = getRepository(Borrow);
    return borrowRepository.find({
      order: {
        id: "ASC"
      }
    });
  }

  // 根据图书编号查找
  async findBorrowByBookId(book_id:string) {
    const borrowRepository = getRepository(Borrow);
    return borrowRepository.find({
      book_id
    })
  }

  // 根据读者编号查找
  async findBorrowByReaderId(reader_id:number) {
    const borrowRepository = getRepository(Borrow);
    return borrowRepository.find({
      reader_id
    })
  }

  // 根据 id 删除借阅记录
  async deleteBorrowByid(id:number) {
    const borrowRepository = getRepository(Borrow);
    return borrowRepository.delete(id)
  }

  // 根据读者 id ，计算出在借阅表中已未归还的，有多少条数据
  async findReaderIdCount(reader_id: number) {
    const borrowRepository = getRepository(Borrow);
    return borrowRepository.count({
      reader_id,
      if_back: 'no'
    })
  }

  // 查找读者已借当前图书的数量（读者 id，图书 id， if_back）
  async findReaderBorrowNowCount(reader_id: number, book_id: string) {
    const borrowRepository = getRepository(Borrow);
    return borrowRepository.count({
      reader_id,
      book_id,
      if_back: 'no'
    })
  }

  // 清空借阅历史
  async clearBorrows() {
    const borrowRepository = getRepository(Borrow);
    return borrowRepository.clear()
  }

}

export default new BorrowServer()